<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>销售记录 - 智慧农业信息管理系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Microsoft YaHei', sans-serif; background-color: #f8f9fa; }
        .navbar { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .navbar-brand, .navbar-nav .nav-link { color: white !important; }
        .sidebar { position: fixed; top: 56px; bottom: 0; left: 0; z-index: 100; padding: 20px 0; background: white; box-shadow: 2px 0 10px rgba(0,0,0,0.1); overflow-y: auto; }
        .sidebar .nav-link { color: #333; padding: 12px 20px; border-left: 3px solid transparent; transition: all 0.3s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { color: #667eea; background-color: #f8f9fa; border-left-color: #667eea; }
        .sidebar .nav-link i { width: 20px; margin-right: 10px; }
        main { margin-top: 56px; padding-top: 20px; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; }
        .modal-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .table-wrapper { background: white; border-radius: 10px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="/index"><i class="fas fa-leaf"></i> 智慧农业信息管理系统</a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text text-white me-3"><i class="fas fa-user-circle"></i> 欢迎，<span th:text="${session.currentUser.realName}">用户</span></span>
                <a class="nav-link text-white" href="/logout"><i class="fas fa-sign-out-alt"></i> 退出</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <nav class="col-md-2 d-md-block sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item"><a class="nav-link" href="/index"><i class="fas fa-home"></i> 首页</a></li>
                        <div th:if="${session.currentUser.role == 'admin'}">
                            <li class="nav-item"><a class="nav-link" href="/user/list"><i class="fas fa-users"></i> 用户管理</a></li>
                        </div>
                        <div th:if="${session.currentUser.role == 'admin' || session.currentUser.role == 'manager'}">
                            <li class="nav-item"><a class="nav-link" href="/field/list"><i class="fas fa-map"></i> 地块管理</a></li>
                            <li class="nav-item"><a class="nav-link" href="/crop/list"><i class="fas fa-seedling"></i> 作物管理</a></li>
                            <li class="nav-item"><a class="nav-link" href="/material/list"><i class="fas fa-boxes"></i> 农资管理</a></li>
                            <li class="nav-item"><a class="nav-link" href="/plan/list"><i class="fas fa-calendar-alt"></i> 种植计划</a></li>
                            <li class="nav-item"><a class="nav-link" href="/farming/list"><i class="fas fa-tractor"></i> 农事记录</a></li>
                            <li class="nav-item"><a class="nav-link" href="/monitor/list"><i class="fas fa-chart-line"></i> 生长监测</a></li>
                            <li class="nav-item"><a class="nav-link" href="/product/list"><i class="fas fa-box"></i> 产品管理</a></li>
                            <li class="nav-item"><a class="nav-link active" href="/sales/list"><i class="fas fa-shopping-cart"></i> 销售记录</a></li>
                            <li class="nav-item"><a class="nav-link" href="/statistics/dashboard"><i class="fas fa-chart-bar"></i> 数据统计</a></li>
                            <li class="nav-item"><a class="nav-link" href="/news/list"><i class="fas fa-bullhorn"></i> 新闻公告</a></li>
                        </div>
                        <li class="nav-item"><a class="nav-link" href="/farm/display"><i class="fas fa-store"></i> 农场展示</a></li>
                    </ul>
                </div>
            </nav>

            <main class="col-md-10 ms-sm-auto px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
                    <h1 class="h2"><i class="fas fa-shopping-cart"></i> 销售记录管理</h1>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#salesModal" onclick="resetForm()">
                        <i class="fas fa-plus"></i> 新增销售
                    </button>
                </div>

                <div class="table-wrapper">
                    <div th:if="${records != null and !records.isEmpty()}">
                        <table class="table table-hover">
                            <thead>
                                <tr><th>销售单号</th><th>产品</th><th>数量</th><th>单价</th><th>总金额</th><th>客户</th><th>销售日期</th><th>操作</th></tr>
                            </thead>
                            <tbody>
                                <tr th:each="r : ${records}">
                                    <td th:text="${r.salesCode}">单号</td>
                                    <td th:text="${r.productName}">产品</td>
                                    <td><span th:text="${r.quantity}">0</span> <span th:text="${r.unit}">单位</span></td>
                                    <td>¥<span th:text="${r.price}">0</span></td>
                                    <td class="text-danger fw-bold">¥<span th:text="${r.totalAmount}">0</span></td>
                                    <td th:text="${r.customerName}">客户</td>
                                    <td th:text="${#temporals.format(r.salesDate, 'yyyy-MM-dd')}">日期</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" th:onclick="'editSales(' + ${r.id} + ')'"><i class="fas fa-edit"></i></button>
                                        <button class="btn btn-sm btn-outline-danger" th:onclick="'deleteSales(' + ${r.id} + ')'"><i class="fas fa-trash"></i></button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div th:if="${records == null or records.isEmpty()}" class="alert alert-info text-center">
                        <i class="fas fa-info-circle fa-2x mb-2"></i>
                        <p>暂无销售记录，请点击"新增销售"按钮添加</p>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <div class="modal fade" id="salesModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-shopping-cart"></i> 销售记录信息</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="salesForm">
                        <input type="hidden" id="salesId" name="id">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">销售单号 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="salesCode" name="salesCode" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">销售日期 <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="salesDate" name="salesDate" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">产品 <span class="text-danger">*</span></label>
                                <select class="form-select" id="productId" name="productId" required onchange="updateProduct()">
                                    <option value="">请选择产品</option>
                                    <option th:each="product : ${products}" th:value="${product.id}" 
                                            th:text="${product.productName + ' (库存:' + product.quantity + product.unit + ')'}">产品</option>
                                </select>
                                <input type="hidden" id="productName" name="productName">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">销售数量 <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="quantity" name="quantity" step="0.1" required onchange="calculateTotal()">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">单位</label>
                                <input type="text" class="form-control" id="unit" name="unit" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">销售单价（元） <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="price" name="price" step="0.01" required onchange="calculateTotal()">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">总金额（元）</label>
                                <input type="number" class="form-control" id="totalAmount" name="totalAmount" step="0.01" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">客户名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="customerName" name="customerName" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">客户电话</label>
                                <input type="text" class="form-control" id="customerPhone" name="customerPhone">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">销售人员</label>
                                <input type="text" class="form-control" id="salesman" name="salesman">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">支付方式</label>
                                <select class="form-select" id="paymentMethod" name="paymentMethod">
                                    <option value="cash">现金</option>
                                    <option value="transfer">转账</option>
                                    <option value="wechat">微信</option>
                                    <option value="alipay">支付宝</option>
                                </select>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">客户地址</label>
                                <input type="text" class="form-control" id="customerAddress" name="customerAddress">
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">备注</label>
                                <textarea class="form-control" id="remark" name="remark" rows="2"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveSales()"><i class="fas fa-save"></i> 保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
        const products = /*[[${products}]]*/ [];
        const currentUser = /*[[${session.currentUser}]]*/ {};

        function resetForm() {
            $('#salesForm')[0].reset();
            $('#salesId').val('');
            $('#salesman').val(currentUser.realName);
            $('#salesDate').val(new Date().toISOString().split('T')[0]);
            $('#paymentMethod').val('transfer');
        }

        function updateProduct() {
            const productId = $('#productId').val();
            const product = products.find(p => p.id == productId);
            if (product) {
                $('#productName').val(product.productName);
                $('#unit').val(product.unit);
                $('#price').val(product.suggestedPrice || product.unitPrice || 0);
                calculateTotal();
            }
        }

        function calculateTotal() {
            const quantity = parseFloat($('#quantity').val()) || 0;
            const price = parseFloat($('#price').val()) || 0;
            const total = (quantity * price).toFixed(2);
            $('#totalAmount').val(total);
        }

        function saveSales() {
            const formData = {
                id: $('#salesId').val() || null,
                salesCode: $('#salesCode').val(),
                productId: parseInt($('#productId').val()),
                productName: $('#productName').val(),
                quantity: parseFloat($('#quantity').val()),
                unit: $('#unit').val(),
                price: parseFloat($('#price').val()),
                totalAmount: parseFloat($('#totalAmount').val()),
                customerName: $('#customerName').val(),
                customerPhone: $('#customerPhone').val(),
                customerAddress: $('#customerAddress').val(),
                salesDate: $('#salesDate').val(),
                salesman: $('#salesman').val(),
                paymentMethod: $('#paymentMethod').val(),
                remark: $('#remark').val()
            };

            $.ajax({
                url: '/sales/save',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.code === 200) {
                        alert('保存成功！');
                        location.reload();
                    } else {
                        alert('保存失败: ' + res.message);
                    }
                },
                error: function() {
                    alert('保存失败，请重试');
                }
            });
        }

        function editSales(id) {
            $.get('/sales/detail/' + id, function(res) {
                if (res.code === 200) {
                    const s = res.data;
                    $('#salesId').val(s.id);
                    $('#salesCode').val(s.salesCode);
                    $('#productId').val(s.productId);
                    $('#productName').val(s.productName);
                    $('#quantity').val(s.quantity);
                    $('#unit').val(s.unit);
                    $('#price').val(s.price);
                    $('#totalAmount').val(s.totalAmount);
                    $('#customerName').val(s.customerName);
                    $('#customerPhone').val(s.customerPhone);
                    $('#customerAddress').val(s.customerAddress);
                    $('#salesDate').val(s.salesDate);
                    $('#salesman').val(s.salesman);
                    $('#paymentMethod').val(s.paymentMethod);
                    $('#remark').val(s.remark);
                    $('#salesModal').modal('show');
                } else {
                    alert('获取销售记录失败');
                }
            });
        }

        function deleteSales(id) {
            if (confirm('确定要删除这条销售记录吗？')) {
                $.ajax({
                    url: '/sales/delete/' + id,
                    type: 'POST',
                    success: function(res) {
                        if (res.code === 200) {
                            alert('删除成功！');
                            location.reload();
                        } else {
                            alert('删除失败: ' + res.message);
                        }
                    },
                    error: function() {
                        alert('删除失败，请重试');
                    }
                });
            }
        }
    </script>
</body>
</html>
